import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login';
import Home from '@/components/Home';
import Welcome from '@/views/Welcome';
import Users from '@/components/users/Users';
import Rights from '@/components/power/Rights';
import Roles from '@/components/power/Roles';
import Cate from '@/components/goods/Cate';
import Params from '@/components/goods/Params';
import List from '@/components/goods/List';
import Add from '@/components/goods/Add';
import Orders from '@/components/order/Orders';
import Report from '@/components/report/Report';

Vue.use(VueRouter)

const routes = [{
    path: "/",
    redirect: "/login"
}, {
    path: "/login",
    component: Login
}, {
    path: "/home",
    component: Home,
    redirect: "/home/welcome",
    children: [{
        path: "welcome",
        component: Welcome
    }, {
        path: "users",
        component: Users
    }, {
        path: "rights",
        component: Rights
    }, {
        path: "roles",
        component: Roles
    }, {
        path: "categories",
        component: Cate
    }, {
        path: "params",
        component: Params
    }, {
        path: "goods",
        component: List
    }, {
        path: "/goods/add",
        component: Add
    }, {
        path: "orders",
        component: Orders
    }, {
        path: "reports",
        component: Report
    }]
}]

const router = new VueRouter({
    routes
})

// 挂载路由导航守卫
/**
 * to 将要访问的路径
 * from 从哪个路径来
 * next() 表示放行，1、next()直接放行 2、next("路径")强制跳转到指定的路径
 */
router.beforeEach((to, from, next) => {
    // 用户访问登录页，直接放行
    if (to.path === "/login") return next();
    // 如果用户没有令牌，强制跳转到登录页
    if (!sessionStorage.getItem("token")) return next("/login");
    // 用户持有令牌，放行
    next();
})

export default router